package com.qidi.service;

import com.alibaba.fastjson.JSON;
import com.qidi.entity.HtmlContent;
import com.qidi.utils.CommonConstant;
import com.qidi.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.AbstractHighlighterBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * HEU
 * Harbin Engineering University
 *
 * @author QiDi
 * @date 2022/12/15 18:42
 */
@Service
public class ContentService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 将这些数据插入到Elasticsearch的索引库中
     *
     * @param keyword
     * @return
     * @throws IOException
     */
    public Boolean addContent(String keyword) throws IOException {

        //应用刚刚编写的HtmlParseUtil解析关键词对应的JD商品信息--获取到JD商品信息对应的contents
        HtmlParseUtils htmlParseUtils = new HtmlParseUtils();
        List<HtmlContent> contents = htmlParseUtils.parseJD(keyword);

        //将刚刚解析的数据放到Elasticsearch中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");    //设置超时时间为2min

        for (HtmlContent content : contents) {
            //将遍历出的content添加到test_jd_goods这个索引中
            bulkRequest.add(
                    new IndexRequest(CommonConstant.INDEX)
                            .source(JSON.toJSONString(content)
                                    , XContentType.JSON));
        }

        //执行批量插入文档的请求  返回一个Response
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        //返回bulk指令是否执行成功
        return !bulk.hasFailures();
    }


    public List<Map<String, Object>> searchPageForHighLight(String keyword, int pageNo, int pageSize) throws IOException {

        if (pageNo <= 1) {
            pageNo = 1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest(CommonConstant.INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精确查找
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false)//关闭多个高亮显示
                .preTags("<span style='color:red'>").postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentField : response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = documentField.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = documentField.getSourceAsMap();   // 原来的结果
            // 解析高亮的字段， 将原来的字段换为我们高亮的字段即可！
            if (title != null) {
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title", n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}











